package service

import (
	"errors"
	"gadmin/model"
	"gorm.io/gorm"
)

func SyncBookmark(bookmarks []model.Bookmark) (err error) {
	var oldBookmarks []model.Bookmark
	cache := make(map[string]model.Bookmark)
	result := model.DB.Find(&oldBookmarks)
	if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
		for _, bookmark := range oldBookmarks {
			cache[bookmark.BookmarkID] = bookmark
		}
	}

	for _, bookmark := range bookmarks {
		if _, exists := cache[bookmark.BookmarkID]; !exists {
			model.DB.Create(&bookmark)
			delete(cache, bookmark.BookmarkID)
		}
	}

	return nil
}
